<template>
  <div>
  <div id='showmes'></div>
  <van-field
          v-model="sendms"
          label="消息"
        />
  <van-button @click='submit'>提交</van-button>
  </div>
</template>

<script>
export default {
    data(){
        return{
            socket:null,
            sendms:'',
            chatname:'',
            showmes:''

        }
    },
    methods: {
        submit(){
            this.socket.send("23423423")
        },
        initweb(){
          this.chatname = this.$route.query.id
         
            // 创建websocket对象，向后台发送请求
 this.socket = new WebSocket("ws://localhost:8000/room/"+this.chatname+"/");

// 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
this.socket.onopen = function (event){
//   let tag = document.createElement("div");
//   tag.innerText = "[连接成功]";
    console.log('连接成功')
}

// 回调函数，客户端接收服务端消息
this.socket.onmessage =  (event)=>{
  console.log(event)
  this.showmes = event.data

}

// 当断开连接时，触发该函数
this.socket.onclose =function (event){
  console.log("关闭")
}

// function sendMessage(){
//   let tag = document.getElementById("txt");
//   socket.send(tag.value);
// }

// function closeMessage(){
//   socket.close();
// }

// function handleKeyPress(event){
//   if (event.keyCode === 13){
//     document.getElementById("send").click();
//     document.getElementById("txt").value = "";
//   }
// }

// document.onkeydown = handleKeyPress;

        }
    },

    mounted() {
        this.initweb()
    },

}
</script>

<style>

</style>